//
//  NCRouterBus.swift
//  NCRouterBus
//
//  Created by zhanwenyan on 2018/10/16.
//  Copyright © 2018年 Newcoretech. All rights reserved.
//

import UIKit

public typealias OnNCRouterIntercept = (_ url: URL?, _ params: [String: Any]?, _ onResult: ((_ res: [String: Any]?) -> Void)?) -> Bool

/// 路由总线，开放给外部调用的方法
public class NCModuleRouterBus {

    private static var moduleRouterMap = [String: NCModuleRouter]()

    private static var routerHookMap = [String: OnNCRouterIntercept]()

    /// 注册模块
    /// - Parameters:
    ///   - module: 模块名称
    ///   - router: NCPageRouter协议实例
    public static func registerModule(module: String, router: NCModuleRouter) {
        objc_sync_enter(moduleRouterMap)
        moduleRouterMap[module] = router
        objc_sync_exit(moduleRouterMap)
    }

    /// 路由是否存在
    ///
    /// - Parameter url: 路由url
    /// - Returns: true: 存在, false: 不存在
    public static func hasRouter(url: URL?) -> Bool {
        if let scheme = url?.scheme, let router = moduleRouterMap[scheme], router.hasRoute(url: url) {
            return true
        } else {
            return false
        }
    }
    
    /// 路由跳转
    ///
    /// - Parameters:
    ///   - url: 路由url
    ///   - vc: 外部控制器
    ///   - skipType: 跳转方式(push / present)
    ///   - params: 跳转参数
    ///   - onResult: route回传数据
    public static func route(to url: URL?, vc: UIViewController, skipType: PageSkipType, params: [String: Any]?, onResult: ((_ res: [String: Any]?) -> Void)?) {
        if let scheme = url?.scheme,
            let pageRouter = moduleRouterMap[scheme],
            let routerVC = pageRouter.routePage(
                url: url,
                params: params,
                onResult: onResult,
                skipType: skipType
            ) {
            if onRouterHook(url: url, params: params, onResult: onResult) {
                switch skipType {
                case .push(let animated):
                    vc.navigationController?.pushViewController(routerVC, animated: animated)
                case .present(let animated, let completion):
                    let routerNC = UINavigationController(rootViewController: routerVC)
                    vc.present(routerNC, animated: animated, completion: completion)
                }
            }
        } else {
            let alertVC = UIAlertController(title: "提示", message: "要访问的页面不存在", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertVC.addAction(okAction)
            vc.present(alertVC, animated: true)
        }
    }

    /// 设置路由Hook
    ///
    /// - Parameters:
    ///   - url: 路由url
    ///   - onIntercept: Hook 方法，该方法若返回true，则继续执行route的页面，若为false，则忽略原来的route页面
    public static func setRouterHook(url: URL?, onIntercept: @escaping OnNCRouterIntercept) {
        guard let urlString = url?.absoluteString else {
            print("urlString 为 空")
            return
        }
        objc_sync_enter(routerHookMap)
        routerHookMap[urlString] = onIntercept
        objc_sync_exit(routerHookMap)
    }

    /// 执行Hook
    ///
    /// - Parameters:
    ///   - url: 路由url
    ///   - params: 参数
    ///   - onResult: 数据回调函数
    /// - Returns: true: 继续执行原route页面， false:则忽略原来的route页面
    public static func onRouterHook(url: URL?, params: [String: Any]?, onResult: ((_ res: [String: Any]?) -> Void)?) -> Bool {
        if let urlString = url?.absoluteString,
            let intercept = routerHookMap[urlString] {
            return intercept(url, params, onResult)
        } else {
            return true
        }
    }
}
